/* Filename: 2-Tcp客户端.c
 * Description:
 * Last modified: humble 2020-11-12 00:15:37
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

static void usage(void);

int main(int argc, char **argv)
{
    char buf[128] = {0};
    ssize_t n =0;
    int sd;
    struct sockaddr_in raddr;

    if(argc != 2){ fprintf(stderr, "argc !=2"); usage(); exit(1); }

    sd = socket(AF_INET, SOCK_STREAM, 0/* IPPROTO_TCP,IPPROTO_SCTP */);
    if(sd < 0){ perror("socket()"); exit(1); }

    //bind(); //可省

    raddr.sin_family = AF_INET;
    raddr.sin_port = htons(8000);
    inet_pton(AF_INET, argv[1], &raddr.sin_addr);

    if(connect(sd, (void *)&raddr, sizeof(raddr)) < 0){ perror("socket()"); exit(1); }

    while(1){
        n = read(STDIN_FILENO, buf, 128);
        buf[n] = 0;
        write(sd, buf, n);
    }

    //recv();
    //close();

    return 0;
}

static void usage(void)
{
#define USAGE "Usage:\n\
  ./client <IP>\n"
    printf(USAGE);
}
